package com.shop.framework.resolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.shop.framework.context.WebContext;
import com.shop.framework.util.Logger;

public class ExceptionMappingResolver implements HandlerExceptionResolver {

	@Override
	@ResponseBody
	public ModelAndView resolveException(
										HttpServletRequest request,
										HttpServletResponse response, 
										Object handler, 
										Exception exception) {
		// TODO Auto-generated method stub
		
		WebContext.remove();
		Logger.getLogger().debug("[CALL] ExceptionMappingResolver : " + request.getContentType());
		Logger.getLogger().debug("REQUEST-CONTENTS-TYPE : " + request.getContentType());
		
		ModelAndView mav = new ModelAndView();
		
		if (request.getContentType() == null) {
			response.setContentType("text/html");
		} else if (request.getContentType().indexOf("json") >= 0) {
			response.setContentType("application/json");
			mav.setViewName("MappingJacksonJsonView");
		} else if (request.getContentType().indexOf("xml") >= 0) {
			response.setContentType("application/xml");
			mav.setViewName("MarshallingView");
		} else if (request.getContentType().indexOf("multipart") >= 0) {
			response.setContentType("application/json");
		} else {
			response.setContentType("text/html");
		}
		
		if (exception instanceof NullPointerException) {
			mav.addObject("PROCESS_MSG", "시스템 오류. 시스템관리자에게 연락하시기 바랍니다");
		} else if (exception instanceof MaxUploadSizeExceededException) {
			mav.addObject("PROCESS_MSG", "파일 사이즈가 너무 큽니다. 최대 10MB 까지 업로드 하실 수 있습니다.");
		} else {
			mav.addObject("PROCESS_MSG", exception.getMessage());
		}
		
		Logger.getLogger().error("Exception occurred.\n ============================\n" ,exception);
		return mav;		
	}

}
